package com.yq.reggie.common;


import com.alibaba.fastjson.JSON;
import com.yq.reggie.controller.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录拦截器
 */
@WebFilter("/*")
@Slf4j
public class LoginFilter  implements Filter {
    //路径匹配器：支持通配符
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取本次请求的uri判断是否放行
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        log.info("拦截到请求: {}",request.getRequestURI());
            //设置放行的资源
            String[] uris=new String[]{"/backend/**","/front/**","/employee/login","/employee/logout","/user/sendMsg","/user/login","/user/logout"};
        for (String uri : uris) {
            //如果本次请求的URI和uri一样则放行
           if( PATH_MATCHER.match(uri,request.getRequestURI())){
            filterChain.doFilter(request,response);
            log.info("放行请求： {}",request.getRequestURI());
            return;
           }
        }
        //（1）判断员工是否已经登录，如果没有登录则跳回登录界面
        Object employee = request.getSession().getAttribute("employee");
        Object user = request.getSession().getAttribute("user");
        if(employee!=null){
            //已经登录
            BaseContext.setCurrentId((Long)request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;}
            //（2）判断用户是否已经登录，如果没有登录则跳回登录界面
           else if(user!=null){
                //已经登录
                BaseContext.setCurrentId((Long)request.getSession().getAttribute("user"));
                filterChain.doFilter(request,response);
                return;
            }else {
                //还没登录，跳回登录页面
                response.getWriter().write(JSON.toJSONString(Result.fail("NOTLOGIN")));
            }
    }
}
